package com.fyp.client.ptma;

import org.apache.http.HttpResponse;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.fyp.client.ptma.model.ApplicationVersion;
import com.fyp.client.ptma.model.Defect;
import com.fyp.client.ptma.utils.Helper;
import com.fyp.client.ptma.utils.NetworkConnectivity;
import com.fyp.client.ptma.xml.ResponseXml;
import com.fyp.client.ptma.xml.XmlBuilder;

public class AddCommentDialogue extends AbstractActivity
{
	private ApplicationVersion version;
	private EditText editVersionComments;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		version = (ApplicationVersion) getIntent().getExtras().get(
				"dataToCarry");

	}

	public void onClick(View view)
	{
		new DefectSubmitTask().execute();
	}

	@Override
	int getContentView()
	{
		// TODO Auto-generated method stub
		return R.layout.add_log_dialogue;
	}

	@Override
	void initViewRefereces()
	{
		editVersionComments = (EditText) findViewById(R.id.editVersionComments);

	}

	private class DefectSubmitTask extends AsyncTask<Integer, Integer, Integer>
	{
		ProgressDialog progressDialog = null;
		private String comment;

		@Override
		protected void onPreExecute()
		{

			super.onPreExecute();
			comment = editVersionComments.getText().toString();
			if (comment.length() == 0)
			{
				cancel(true);
				return;
			}

			progressDialog = ProgressDialog.show(AddCommentDialogue.this, "",
					"Submitting...");
		}

		@Override
		protected void onPostExecute(Integer result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			switch (result)
			{
			case ResponseXml.OK:

				getIntent().putExtra("dataToReturn", defect);
				setResult(RESULT_OK, getIntent());
				finish();
				showShortToast("Defect Submitted..");
				break;

			default:
				break;
			}
			progressDialog.dismiss();
		}

		Defect defect;

		@Override
		protected Integer doInBackground(Integer... params)
		{
			String url = getString(R.string.WS_URL)
					+ getString(R.string.WS_SUBMIT_DEFECT);
			try
			{
				defect = new Defect();
				defect.setComment(comment);
				defect.setAppVersion(version);
				defect.setCommenterCode(Defect.DOWNLOADER);
				HttpResponse response = NetworkConnectivity
						.performPostOperation(url,
								XmlBuilder.getXmlForDefectSubmit(defect));
				ResponseXml wsResponse = Helper.getResponseObject(response);
				return wsResponse.getStatusCode();
			} catch (Exception e)
			{
				e.printStackTrace();
				return 0;
			}

		}

	}

}
